<template>
  <el-dialog
    title="营销任务详情"
    :append-to-body="true"
    @open="getInit"
    :visible.sync="show"
    top="5vh"
    width="900px"
    :before-close="handleClose"
  >
    <el-scrollbar class="dialog-scrollbar">
      <div class="padding-right20">
        <el-row :gutter="40" class="panel-group">
          <el-col :xs="12" :sm="12" :lg="6" class="card-panel-col">
            <div
              class="card-panel"
              @click="handleSetLineChartData('newVisitis')"
            >
              <div style="margin: 15px 0px; font-size: 17px">提交发送</div>
              <el-progress
                type="circle"
                :stroke-width="10"
                :format="getSendContent"
                :percentage="sendContentPercentage"
              ></el-progress>
              <div class="card-panel-content">
                <p>总数：{{ this.info.submitNum }}</p>
                <p>预扣：暂无</p>
                <p>消耗：暂无 0%</p>
              </div>
            </div>
          </el-col>
          <el-col :xs="12" :sm="12" :lg="6" class="card-panel-col">
            <div
              class="card-panel"
              @click="handleSetLineChartData('newVisitis')"
            >
              <div style="margin: 15px 0px; font-size: 17px">智能过滤</div>
              <el-progress
                type="circle"
                :stroke-width="10"
                :format="getFilterContent"
                :percentage="filterContentPercentage"
              ></el-progress>
              <div class="card-panel-content">
                <p>总数：{{ this.info.submitNum }}</p>
                <p>清洗：暂无 0%</p>
              </div>
            </div>
          </el-col>
          <el-col :xs="12" :sm="12" :lg="6" class="card-panel-col">
            <div
              class="card-panel"
              @click="handleSetLineChartData('newVisitis')"
            >
              <div style="margin: 15px 0px; font-size: 17px">发信成功</div>
              <el-progress
                type="circle"
                :stroke-width="10"
                :format="getSendSuccessContent"
                :percentage="sendSuccessContentPercentage"
              ></el-progress>
              <div class="card-panel-content">
                <p>送达：{{ this.info.sendingNum }} 100%</p>
                <p>阅读：{{ this.info.openNum }} 100%</p>
                <p>回复：{{ this.info.replyNum }} 100%</p>
              </div>
            </div>
          </el-col>
          <el-col :xs="12" :sm="12" :lg="6" class="card-panel-col">
            <div
              class="card-panel"
              @click="handleSetLineChartData('newVisitis')"
            >
              <div style="margin: 15px 0px; font-size: 17px">退信/失败</div>
              <el-progress
                type="circle"
                :stroke-width="10"
                :format="getFiledContent"
                :percentage="sendFailedContentPercentage"
              ></el-progress>
              <div class="card-panel-content !w-30">
                <p>失败：暂无 100%</p>
                <p>硬退：暂无 100%</p>
                <p>软退：暂无 100%</p>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
      <div>
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="发送日志" name="first" class="padding-right20">
            <el-card shadow="always">
              <div>
                <div
                  :id="id"
                  :class="className"
                  :style="{ height: height, width: width }"
                />
              </div>
              <el-tabs
                v-model="activeChildrenName"
                @tab-click="handleChildrenTabClick"
              >
                <el-tab-pane label="全部" name="first-first"> </el-tab-pane>
                <el-tab-pane label="阅读" name="first-second"> </el-tab-pane>
                <el-tab-pane label="未阅读" name="first-third"> </el-tab-pane>
                <el-tab-pane label="回复" name="first-fifth"> </el-tab-pane>
                <el-tab-pane label="发送失败/退订" name="first-sixth">
                </el-tab-pane>
              </el-tabs>
              <el-table
                :data="emailTableData"
                height="700px"
                style="width: 100%"
              >
                <el-table-column
                  align="center"
                  prop="receiverEmail"
                  label="邮件（联系人，邮箱）"
                  width="180"
                >
                </el-table-column>
                <el-table-column align="center" label="发送邮箱">
                  <template slot-scope="{ row }">
                    <template v-if="row.sendingType === 2">
                      服务器代发
                    </template>
                    <template v-else>
                      {{ row.senderEmail }}
                    </template>
                  </template>
                </el-table-column>
                <el-table-column
                  align="center"
                  prop="errorMessage"
                  label="状态"
                >
                  <template slot-scope="{ row }">
                    <template v-if="!row.state || row.isUnsub">
                      <span class="text-red-500 mr-1">失败</span>
                      {{ row.errorMessage ? row.errorMessage : '未知错误' }}
                    </template>
                    <template v-else>
                      <span v-if="!row.isOpen">
                        <span class="text-green-500">已发送</span>-<span
                          class="text-gray-500"
                          >未读</span
                        >
                      </span>
                      <span v-else class="text-green-500">已读</span>
                    </template>
                  </template>
                </el-table-column>
                <el-table-column
                  align="center"
                  prop="createdAt"
                  label="发送时间"
                >
                </el-table-column>
              </el-table>
            </el-card>
          </el-tab-pane>
          <el-tab-pane label="邮件内容" name="fifth" class="padding-right20">
            <el-card shadow="always">
              <div style="text-align: center; font: bold; font-size: 20px">
                主题：{{ this.info.emailSubject }}
              </div>
              <el-divider></el-divider>
              <div v-html="this.info.emailContent" />
            </el-card>
          </el-tab-pane>
          <el-tab-pane label="操作日志" name="sixth" class="padding-right20">
            <el-card shadow="always">
              <template>
                <el-table :data="operateLogData" style="width: 100%">
                  <el-table-column
                    label="序号"
                    align="center"
                    width="50"
                    type="index"
                  />
                  <el-table-column align="center" label="操作用户" width="180">
                    <template slot-scope="{ row }">
                      <b>{{ row.operateUserName }}</b>
                    </template>
                  </el-table-column>
                  <el-table-column align="center" label="操作时间" width="180">
                    <template slot-scope="{ row }">
                      <b>{{ row.createdAt }}</b>
                    </template>
                  </el-table-column>
                  <el-table-column
                    align="center"
                    show-overflow-tooltip
                    label="操作内容"
                  >
                    <template slot-scope="{ row }">
                      <el-tooltip
                        effect="dark"
                        :content="row.operationContent"
                        placement="top"
                      >
                        <b>{{ row.operationContent }}</b>
                      </el-tooltip>
                    </template>
                  </el-table-column>
                </el-table>
              </template>
            </el-card>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-scrollbar>
  </el-dialog>
</template>
<script>
import { getAction, postAction } from '@/api/common'
import * as echarts from 'echarts'
export default {
  name: 'showSendDataTracking',
  props: {
    show: {
      type: Boolean,
      default: false,
    },
    rowId: {
      type: Number,
      default: 0,
    },
    className: {
      type: String,
      default: 'chart',
    },
    id: {
      type: String,
      default: 'chart',
    },
    width: {
      type: String,
      default: '800px',
    },
    height: {
      type: String,
      default: '300px',
    },
  },
  components: {},
  data: function () {
    return {
      /// //////////////////////////////////////////////////////////////////////////////////
      tableData: [0, 0, 0, 0, 0, 0],
      info: {
        submitNum: 0,
        sendingNum: 0,
        replyNum: 0,
        openNum: 0,
        emailContent: '',
      },
      listQuery: {
        id: 0,
      },
      emailData: [],
      emailTableData: [],
      operateLogData: [],
      /// //////////////////////////////////////////////////////////////////////////////////
      emailDataRead: [],
      emailDataUnread: [],
      emailDataReply: [],
      emailDataFailedAndReturn: [],
      sendContentPercentage: 0,
      filterContentPercentage: 0,
      sendSuccessContentPercentage: 0,
      sendFailedContentPercentage: 0,
      activeName: 'first',
      activeChildrenName: 'first-first',
      fileList: [
        {
          name: 'food.jpeg',
          url:
            'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100',
        },
        {
          name: 'food2.jpeg',
          url:
            'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100',
        },
      ],
      form: {
        Title: '',
        Addresser: '',
        ShowAsEmail: false,
        ReplyEmail: '',
        Addressee: null,
        EmailSubject: '{}',
        TimingTransmission: null,
      },
    }
  },
  watch: {
    show(val) {
      this.$emit('update:show', val)
    },
  },
  created() {
    // console.log('created')
  },
  mounted() {
    // console.log('mounted')
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },

  methods: {
    /// //////////////////////////////////////////////////////////////////////////////////
    getInit() {
      this.getData()
    },
    getData() {
      this.listLoading = true
      getAction({ id: this.rowId }, 'EmailMarketing/info')
        .then(({ data }) => {
          this.info = data
          if (data.state === 3 || data.state === 4) {
            this.sendContentPercentage = this.toFixPercentage(
              parseInt((this.info.sendingNum / this.info.submitNum) * 100)
            ) // toFixed返回字符串类型，*1 转化为Number
            this.filterContentPercentage = 100
            this.sendSuccessContentPercentage = this.toFixPercentage(
              parseInt((this.info.sendingNum / this.info.submitNum) * 100)
            )
            this.sendFailedContentPercentage = this.toFixPercentage(
              100 - this.sendSuccessContentPercentage
            )
            this.tableData = [
              this.info.sendingNum,
              this.info.openNum,
              this.info.sendingNum - this.info.openNum,
              this.info.replyNum,
              this.info.submitNum - this.info.sendingNum,
            ]
          } else {
            this.sendContentPercentage = 0
            this.filterContentPercentage = 100
            this.sendSuccessContentPercentage = 0
            this.sendFailedContentPercentage = 0
            this.tableData = [
              this.info.sendingNum,
              this.info.openNum,
              this.info.sendingNum - this.info.openNum,
              this.info.replyNum,
              this.info.submitNum - this.info.sendingNum,
            ]
            this.tableData = [0, 0, 0, 0, 0]
          }
        })
        .then(() => {
          this.initChart()
        })
        .catch(() => {
          // console.log('error')
        })
      getAction(
        { id: this.rowId },
        'EmailSendHistory/emailMarketingHistory'
      ).then(({ data }) => {
        this.emailData = [...data]
        this.emailTableData = [...data]
      })
      this.listLoading = false
      this.$nextTick(() => {
        // console.log(this.info)
      })
    },
    toFixPercentage(percentage) {
      if (percentage > 100) {
        percentage = 100
      }
      if (percentage < 0) {
        percentage = 0
      }
      return percentage
    },
    handleClose() {
      this.$emit('update:show', false)
      this.operateLogData = []
      this.activeName = 'first'
      this.activeChildrenName = 'first-first'
    },
    handleSetLineChartData(val) {
      console.log('setLineChartData', val)
    },
    handleChildrenTabClick(tab, event) {
      // console.log(this.emailData)
      if (tab.name === 'first-first') {
        this.emailTableData = this.emailData
      }

      if (tab.name === 'first-second') {
        this.emailTableData = this.emailData.filter((m) => m.isOpen)
      }

      if (tab.name === 'first-third') {
        this.emailTableData = this.emailData.filter(
          (m) => !m.isOpen && m.state && !m.isUnsub
        ) // 已经发送的和没有改变成已读状态的就是未读的---销毁图片的时候一次机会进行修改或者回复邮件后进行修改
      }

      if (tab.name === 'first-fifth') {
        this.emailTableData = this.emailData.filter((m) => m.state === 4)
      }

      if (tab.name === 'first-sixth') {
        this.emailTableData = this.emailData.filter(
          (m) => !m.state || m.isUnsub
        )
      }
    },
    /// //////////////////////////////////////////////////////////////////////////////////

    // 编辑和弹出的初始化页面

    handleChange(file, fileList) {
      this.fileList = fileList.slice(-3)
    },
    getSendContent(percentage) {
      return '📧 \n' + `${percentage}%`
    },
    getFilterContent(percentage) {
      return '💱 \n' + `${percentage}%`
    },
    getSendSuccessContent(percentage) {
      return '✅ \n' + `${percentage}%`
    },
    getFiledContent(percentage) {
      return '❌ \n' + `${percentage}%`
    },
    submitForm() {
      postAction(this.form, 'EmailMarketing/Create').then((res) => {
        // console.log(res)
        if (res.code === 20000) {
          this.$message({
            message: '新建营销任务成功',
            type: 'success',
          })
        } else {
          this.$message({
            message: '新建营销任务失败',
            type: 'warning',
          })
        }
        this.$emit('update:show', false)
      })

      // const res = await
      // this.$message.success('提交成功')
      // this.$emit('update:show', false)
      // this.$emit('closeAction')
    },
    handleClick(tab, event) {
      // console.log(tab, event)
      if (tab.name === 'sixth') {
        this.openOperateLogPage()
      }
    },
    initChart() {
      this.chart = echarts.init(document.getElementById(this.id))
      const xAxisData = []
      const data = []
      const data2 = []
      for (let i = 0; i < 50; i++) {
        xAxisData.push(i.toString())
        data.push((Math.sin(i / 5) * (i / 5 - 10) + i / 6) * 5)
        data2.push((Math.sin(i / 5) * (i / 5 + 10) + i / 6) * 3)
      }
      const option = {
        xAxis: {
          type: 'category',
          data: ['发送数', '阅读', '未读', '回复', '发送失败/退订'],
        },
        yAxis: {
          type: 'value',
        },
        series: [
          {
            data: this.tableData,
            type: 'bar',
            showBackground: true,
            backgroundStyle: {
              color: 'rgba(180, 180, 180, 0.2)',
            },
          },
        ],
        grid: {
          x: 50,
          y: 20,
          x2: 20,
          y2: 30,
        },
      }
      this.chart.setOption(option)
    },
    openOperateLogPage() {
      if (!(this.operateLogData.length === 0)) {
        return
      }
      // console.log('打开日志页面')
      this.listLoading = true
      getAction({ id: this.rowId }, 'EmailMarketingLog/Index')
        .then(({ data }) => {
          this.operateLogData = data
        })
        .catch(() => {
          // console.log('error')
        })
      this.listLoading = false
      this.$nextTick(() => {
        // console.log('nextTick')
      })
    },
  },
}
</script>

<style scoped>
/deep/ .el-dialog__body {
  padding: 20px 0px 20px 20px;
}
</style>
<style lang="scss" scoped>
.panel-group {
  .card-panel-col {
    margin-bottom: 10px;
  }
  .card-panel {
    text-align: center;
    height: 290px;
    cursor: pointer;
    font-size: 15px;
    position: relative;
    overflow: hidden;
    color: #666;
    background: #fff;
    box-shadow: 4px 4px 40px rgba(0, 0, 0, 0.05);
    border-color: rgba(0, 0, 0, 0.05);

    .card-panel-content {
      @apply text-left mt-5 mx-auto w-25;
    }
  }
  .card-panel-icon-wrapper {
    color: #fff;
  }
  .icon-people {
    background: #40c9c6;
  }
  .icon-message {
    background: #36a3f7;
  }
  .icon-money {
    background: #f4516c;
  }
  .icon-shopping {
    background: #34bfa3;
  }
}

.icon-people {
  color: #40c9c6;
}

.icon-message {
  color: #36a3f7;
}

.icon-money {
  color: #f4516c;
}

.icon-shopping {
  color: #34bfa3;
}

.dialog-scrollbar {
  height: 75vh;
}

.padding-right20 {
  padding-right: 20px;
}
</style>
